package com.isnoam.calendar.view

import android.content.Context
import android.util.AttributeSet
import com.isnoam.calendar.base.BaseCalendarView
import com.isnoam.calendar.base.BaseMonthView
import com.isnoam.calendar.bean.DateInfo
import com.isnoam.calendar.bean.ViewAttrs
import com.isnoam.calendar.listener.OnDateSelectedListener
import com.isnoam.calendar.listener.OnSingleDateSelectedListener
import com.isnoam.calendar.view.month.SingleMonthView
import java.util.*

/**
 * 单选日历控件
 */
class SingleCalendarView(
    context: Context, attrs: AttributeSet
) : BaseCalendarView(context, attrs) {

    private var listener: OnSingleDateSelectedListener? = null

    /**
     * 设置选中日期
     */
    fun setSelectedDate(selectedDate: DateInfo) {
        setDateRange(selectedTimeInMillis = selectedDate.timeInMillis())
    }

    /**
     * 创建月份
     */
    override fun createMonthView(
        position: Int, currentMonth: Calendar, viewAttrs: ViewAttrs
    ): BaseMonthView {
        val monthView = SingleMonthView(context, currentMonth, position, viewAttrs)
        monthView.selectedDate = DateInfo().toDate(selectedDate)
        monthView.onDateSelectedListener = object : OnDateSelectedListener {
            override fun onDateSelected(
                dateInfo: DateInfo, changeMonth: Boolean, monthPosition: Int
            ) {
                updateDateSelected(dateInfo, changeMonth, monthPosition)
                listener?.let { it(this@SingleCalendarView, dateInfo) }
            }
        }
        return monthView
    }

    fun setOnSingleDateSelectedListener(listener: OnSingleDateSelectedListener) {
        this.listener = listener
    }
}